<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=
    , initial-scale=1.0">
    <title>How to finsh a Promise object</title>
</head>
<body>
    <script>//简易版promise
        const PENDING = 'pending';
        const RESOLVED = 'resolved';//onfufilled
        const REJECTED = 'rejected';
        function MyPromise(excutor){
            const self = this;
            self.value = null;
            self.state = PENDING;
            self.onResloveCallbacks = [];
            self.onRejectCallbacks = [];

            //定义 promise两个函数参数 resolve 和 reject 方法

            function resolve(value){
                if(self.state === PENDING){
                    self.state = RESOLVED;
                    self.value = value;
                    self.onResloveCallbacks.map(cb => cb(self.value))
                }
            }

            function reject(value){
                if(self.state === PENDING){
                    self.state = REJECTED;
                    self.value = value;
                    self.onRejectCallbacks.map(cb => cb(self.value))
                }
            }

            //下面我们进行错误处理

            try{
                excutor(resolve,reject)
            }catch(e){
                reject(e)
            }

            //下面更新then方法，其实因为 then比setTimeout先执行 所以我们需要 保存回调函数到 回调数组里，然后进行提取用于模仿 then方法
            MyPromise.prototype.then = function (onFulfilled,onRejected){
                const self = this;
                onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v 
                onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r }
                if(self.state === PENDING){
                    self.onResloveCallbacks.push(onFulfilled)
                    self.onRejectCallbacks.push(onRejected)
                }
            }
        }
    </script>
</body>
</html>